﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mscook.mvc.Filters;
using mscook.mvc.Models;
using mscook.core.services;
using mscook.mvc.Core;
using mscook.core.domain;
using System.Security.Principal;
using mscook.core.repositories;
using mscook.core;
using System.Text.RegularExpressions;
namespace mscook.mvc.Areas.weblogin.Controllers
{
    [UserAuthorizeAttribute(Roles = "admin,editor")]
    public class BaseController : Controller
    {
        private IResourceOfTypeRepository iResourceOfTypeRepository = UnityHelper.UnityToT<IResourceOfTypeRepository>();
        private IResourceTypeRepository iResourceTypeRepository = UnityHelper.UnityToT<IResourceTypeRepository>();
        private IImageSettingFactory iImageSettingFactory = UnityHelper.UnityToT<IImageSettingFactory>();
        private IRelativeInfoRepository iRelativeInfoRepository = UnityHelper.UnityToT<IRelativeInfoRepository>();

        public BaseController(ILoginUserService loginUserService)
        {
            this.LoginUserService = loginUserService;

        }
        //
        // GET: /weblogin/Base/
        public ILoginUserService LoginUserService
        {
            get;
            protected set;
        }
        public LoginUser CurrentUser
        {
            get
            {
                LoginUser loginUser;


                var loginRepo = this.LoginUserService;

                string loginId = this.HttpContext.User.Identity.Name;

                loginUser = loginRepo.SelectLoginUserByLoginName(loginId);


                return loginUser;
            }
        }


        protected ActionResult RedirectToIndex()
        {
            return RedirectToAction("Index");
        }

        protected void InitNavBar()
        {
            ViewData[ViewDataKeys.USERNAME] = CurrentUser.LoginName;
            ViewData[ViewDataKeys.USERROLE] = CurrentUser.UserRole;
        }

        protected void SaveResourceType(Entity entity, string resourceTypes = "")
        {
            string[] typeArr = resourceTypes.Split(',');
            IList<string> exitType = iResourceTypeRepository.GetExitTypeIds(entity.Id);//2013-11-29 JohnHash 数据量较少，采用内存判断是否存在

            for (int i = 0; i < typeArr.Length; i++)
            {
                string typeId = typeArr[i];
                if (!string.IsNullOrEmpty(typeId) && !exitType.Contains(typeId))//2013-11-29处理tyId为空时造成的异常
                {
                    ResourceType resourceType = iResourceTypeRepository.Get(typeId);
                    ResourceOfType resourceOfType = new ResourceOfType { ResourceId = entity.Id, ResourceType = resourceType };
                    iResourceOfTypeRepository.SaveOrUpdate(resourceOfType);
                }
                else
                {
                    exitType.Remove(typeId);
                }
            }
            foreach (string removeTypeId in exitType)
            {
                ResourceOfType resourceOfType = iResourceOfTypeRepository.GetByResourceAndType(entity.Id, removeTypeId);
                if (resourceOfType != null)
                {
                    iResourceOfTypeRepository.PhysicsDelete(resourceOfType.Id);
                }
            }
        }

        protected IList<ResourceType> GetResourceType(string entityId)
        {
            return iResourceTypeRepository.GetTypeByResource(entityId);
        }
        protected IList<ResourceType> GetResourceType(PurchasedCategory category, string entityId)
        {
            return iResourceTypeRepository.GetTypeByResource(category, entityId);
        }


        protected IList<RelativeInfo> GetRelativeInfo(string entityId)
        {
            return iRelativeInfoRepository.GetByResourceId(entityId).OrderBy(o=>o.EntityIndex).ToList();
        }
        protected void SaveRelativeInfo(FormCollection collections, string entityId,string SectionName)
        {
            var validRelatedContents = from s in collections.AllKeys
                                       where s.IndexOf("relatedInfo_content[") != -1 && s != "relatedInfo_content[0]"
                                       select new string[] { s, string.Format("relatedInfo_content_image[{0}]", new Regex("\\d").Match(s).Value), string.Format("existed_relatedInfo_content_image[{0}]", new Regex("\\d").Match(s).Value), string.Format("relatedInfo_id[{0}]", new Regex("\\d").Match(s).Value),new Regex("\\d").Match(s).Value };
            /*
             * 2013-12-03 lampard
             * 0:相关内容
             * 1:修改后的图片
             * 2：已经存在的图片
             * 3：相关的id(判断是修改还是新添加)
             * 4:顺序
             * */

            foreach (var element in validRelatedContents)
            {
                HttpPostedFileBase file = Request.Files.Get(element[1]);
                RelativeInfo relativeInfo;
                string exitedImage = collections[element[2]];
                string content = collections[element[0]];
                string id = collections[element[3]];
                string index = element[4];

                if (!string.IsNullOrEmpty(content))
                {
                    if (string.IsNullOrEmpty(id))//新添加执行的操作
                    {
                        relativeInfo = new RelativeInfo();
                        relativeInfo.ResourceID = entityId;
                        relativeInfo.EntityIndex = int.Parse(index);
                    }
                    else//修改执行的操作
                    {
                        relativeInfo = iRelativeInfoRepository.Get(id);
                    }

                    if (relativeInfo != null)
                    {
                        relativeInfo.Content = content;
                        relativeInfo.ImagePath = SaveRelativeInfoImage(file, exitedImage, SectionName);
                        iRelativeInfoRepository.SaveOrUpdate(relativeInfo);
                    }
                }


            }
        }


        public ActionResult DeleteRelativeInfo(string id)
        {
            iRelativeInfoRepository.PhysicsDelete(id);
            return new JsonResult { Data = true };

        }

        private string SaveRelativeInfoImage(HttpPostedFileBase file, string exitedImage,string SectionName)
        {
            string relatedInfo_content_image = string.Empty;
            if (file != null && file.FileName != string.Empty)
            {
                relatedInfo_content_image = iImageSettingFactory.CreateBatchSizedImage(SectionName, file.FileName, file.InputStream);
            }
            else if (!string.IsNullOrEmpty(exitedImage))
            {
                relatedInfo_content_image = exitedImage;//如果图片上传不存在，则不修改图片
            }
            return relatedInfo_content_image;
        }


    }
}
